import { createVNode, render } from 'vue';
import Toast from './Toast.vue';

let toastContainer = null;
let toastInstances = [];
let toastId = 0;

const createToastContainer = () => {
  if (!toastContainer) {
    toastContainer = document.createElement('div');
    toastContainer.className = 'toast-container';
    toastContainer.style.position = 'fixed';
    toastContainer.style.top = '0';
    toastContainer.style.left = '0';
    toastContainer.style.width = '100%';
    toastContainer.style.height = '0';
    toastContainer.style.overflow = 'visible';
    toastContainer.style.display = 'flex';
    toastContainer.style.flexDirection = 'column';
    toastContainer.style.alignItems = 'center';
    toastContainer.style.zIndex = '9999';
    document.body.appendChild(toastContainer);
  }
};

const useToast = {
  show(options) {
    if (typeof options === 'string') {
      options = { message: options };
    }

    createToastContainer();
    
    // 创建一个新的容器元素用于这个Toast实例
    const instanceContainer = document.createElement('div');
    instanceContainer.className = 'toast-instance';
    instanceContainer.style.position = 'relative';
    instanceContainer.style.marginTop = '16px';
    instanceContainer.style.width = '100%';
    instanceContainer.style.display = 'flex';
    instanceContainer.style.justifyContent = 'center';
    toastContainer.appendChild(instanceContainer);
    
    // 生成唯一ID
    const id = toastId++;
    
    const vnode = createVNode(Toast, {
      ...options,
      onDestroy: () => {
        // 移除实例
        const index = toastInstances.findIndex(item => item.id === id);
        if (index !== -1) {
          toastInstances.splice(index, 1);
        }
        // 移除DOM
        toastContainer.removeChild(instanceContainer);
      }
    });
    
    render(vnode, instanceContainer);
    
    // 保存实例信息
    toastInstances.push({
      id,
      el: instanceContainer,
      vnode
    });
  },

  info(message, duration) {
    this.show({ message, type: 'info', duration });
  },

  success(message, duration) {
    this.show({ message, type: 'success', duration });
  },

  error(message, duration) {
    this.show({ message, type: 'error', duration });
  },

  warning(message, duration) {
    this.show({ message, type: 'warning', duration });
  }
};

export default useToast;